package com.jw.debezuim.utils;


import lombok.extern.slf4j.Slf4j;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 *
 */
@Slf4j
public class AES {

    /**
     * 算法/模式/填充
     */
    private static final String CIPHER_INSTANCE = "AES/ECB/PKCS5Padding";

    /**
     * AES key的默认长度
     */
    private static int keyLength = 16;

    /**
     * 编码模式-UTF-8
     */
    private static final String ENCODE = "utf-8";

    /**
     * 编码算法AES
     */
    private static final String ENCYPT_AES = "AES";

    /**
     * 初始化key16位
     */
    public static final String DEFAULT_KEY = "BALGEALG12345678";

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 加密方法
     *
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String sSrc, String sKey) {
        if (sKey == null) {
            log.info("key为空！");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != keyLength) {
            log.info("Key长度不是16位");
            return null;
        }
        byte[] encrypted = new byte[0];
        try {
            byte[] raw = sKey.getBytes(ENCODE);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ENCYPT_AES);
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            encrypted = cipher.doFinal(sSrc.getBytes(ENCODE));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        //此处转为16进制字符串
        return parseByte2HexStr(encrypted);
    }

    /**
     * 用默认的key加密
     *
     * @param sSrc
     * @return
     * @throws Exception
     */
    public static String encrypt(String sSrc) {
        if (DEFAULT_KEY == null) {
            log.info("key为空！");
            return null;
        }
        // 判断Key是否为16位
        if (DEFAULT_KEY.length() != keyLength) {
            log.info("Key长度不是16位");
            return null;
        }
        byte[] encrypted = new byte[0];
        try {
            byte[] raw = DEFAULT_KEY.getBytes(ENCODE);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ENCYPT_AES);
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            encrypted = cipher.doFinal(sSrc.getBytes(ENCODE));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        //此处转为16进制字符串
        return parseByte2HexStr(encrypted);
    }

    /**
     * 解密功能
     *
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc, String sKey) {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != keyLength) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes(ENCODE);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ENCYPT_AES);
            Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            return getOriginalString(sSrc, cipher);
        } catch (Exception ex) {
            log.info(ex.toString());
            return null;
        }
    }


    /**
     * 用默认的key解密
     *
     * @param sSrc
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc) {
        try {
            // 判断Key是否正确
            if (DEFAULT_KEY == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (DEFAULT_KEY.length() != keyLength) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = DEFAULT_KEY.getBytes(ENCODE);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ENCYPT_AES);
            Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            return getOriginalString(sSrc, cipher);
        } catch (Exception ex) {
            log.info(ex.toString());
            return null;
        }
    }


    private static String getOriginalString(String sSrc, Cipher cipher) {
        try {
            byte[] original = cipher.doFinal(parseHexStr2Byte(sSrc));
            String originalString = new String(original, ENCODE);
            return originalString;
        } catch (Exception e) {
            log.info(e.toString());
            return null;
        }
    }

    /**
     * 使用默认的key加密entity
     *
     * @param object
     * @return
     */
    public static Object entityEncrypt(Object object) {
        Class<?> clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        if (null == fields) {
            return object;
        }
        if (fields.length == 0) {
            return object;
        }
        try {
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                String name = fields[i].getName();
                Object value = fields[i].get(object);
                if (name.contains("Enc") && null != value) {
                    Field field = clazz.getDeclaredField(name);
                    field.setAccessible(true);
                    value = encrypt(String.valueOf(value));
                    field.set(object, value);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } finally {
            return object;
        }
    }

    /**
     * 使用默认的key为entity解密
     *
     * @param object
     * @return
     */
    public static Object entityDecrypt(Object object) {
        Class<?> clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        if (null == fields) {
            return object;
        }
        if (fields.length == 0) {
            return object;
        }
        try {
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                String name = fields[i].getName();
                Object value = fields[i].get(object);
                if (name.contains("Enc")) {
                    Field field = clazz.getDeclaredField(name);
                    field.setAccessible(true);
                    if (null == value || "".equals(value) || "BF5E7E0A11553377030EBA81964A6BEA".equals(value)) {
                        field.set(object, "0");
                    } else {
                        value = decrypt(String.valueOf(value));
                        field.set(object, value);
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } finally {
            return object;
        }
    }

    public static void main(String[] args) throws Exception {

        // 需要加密的字串
        String cSrc = "11243546";
        System.out.println(cSrc);
        // 加密
        String encrypt = AES.encrypt(cSrc);
        System.out.println("加密后的字串是：" + encrypt);
        // 解密
        System.out.println("解密开始时间" + System.currentTimeMillis());
        String decrypt = AES.decrypt(encrypt);
        System.out.println("解密后的字串是：" + decrypt);
        System.out.println("解密结束时间" + System.currentTimeMillis());

    }
}
